<?php
namespace app\api\logic;
use app\common\server\UrlServer;
use app\common\server\ConfigServer;
use app\api\model\Goods;
use think\Db;
use think\facade\Cache;

class GoodsLogic{

     //商品列表
    public static function getGoodsList($user_id,$get,$page,$size){
        $where = [];
        $order = [];
        $where[] = ['status','=',1];
        $where[] = ['delete_time','=',0];

        $goods = new Goods();
        //分类筛选
        if(isset($get['category_id']) && $get['category_id']){
            $where[] = ['first_category_id|second_category_id|third_category_id','=',$get['category_id']];
        }

        //关键词搜索
        if(isset($get['keyword']) && $get['keyword']){
            $where[] = [ 'name', 'like', "%{$get['keyword']}%" ];
            //记录关键词
            if($user_id){
                //self::recordKeyWord(trim($get['keyword']),$user_id);
            }
        }
        //销量排序
        if(isset($get['sales_sum']) && $get['sales_sum']){
            $order['sales_sum'] = $get['sales_sum'];
        }
        //价格排序
        if(isset($get['price']) && $get['price']){
            $order['min_price'] = $get['price'];
        }

        $order['sort'] = 'desc';
        $order['id'] = 'desc';

        $goods_count = $goods
                    ->where($where)
                    ->count();

        $goods_list = $goods
                    ->where($where)
                    ->page($page,$size)
                    ->order($order)
                    ->field('id,name,image,min_price as price,integral,market_price,sales_sum+virtual_sales_sum as sales_sum,sort')
                ->select();

        $more = is_more($goods_count,$page,$size);  //是否有下一页

        $data = [
            'list'          => $goods_list,
            'page_no'       => $page,
            'page_size'     => $size,
            'count'         => $goods_count,
            'more'          => $more
        ];
        return $data;

    }

    //首页轮播图
    public static function getBanner(){
        $banner = Cache::get('banner');
        if(!$banner){
            $banner = Db::name('slide')->where(['status'=>1,'delete_time'=>0])->order('sort desc,id desc')->select();
            Cache::set('banner',$banner,3600);
        }
        return $banner;
        
    }

    //记录搜索关键词
    public static function recordKeyWord($keyword,$user_id){
        $record = Db::name('search_record')->where(['user_id'=>$user_id,'keyword'=>$keyword,'delete_time'=>0])->find();

        if($record){
            return Db::name('search_record')->where(['id'=>$record['id']])->update(['count'=>Db::raw('count+1'),'update_time'=>time()]);
        }
        return Db::name('search_record')->insert(['user_id'=>$user_id,'keyword'=>$keyword]);
    }


    //商品详情
    public static function getGoodsDetail($id,$user_id){

        $goods = Goods::get(['id'=>$id,'status'=>1],['goods_image','goods_item']);
        if(empty($goods)){
            return [];
        }
        //点击量
        // $goods->click_count = $goods->click_count  + 1;
        $goods->save();
        $goods->sales_sum += $goods->virtual_sales_sum;
        $goods->is_collect = 0;
        $goods->member_price = 0;
        $goods->append(['order_give_integral', 'commission_price']);

        if($user_id) {
            //是否收藏
            // $collect = Db::name('goods_collect')->where(['user_id'=>$user_id,'goods_id'=>$id])->find();
            // $goods->is_collect= $collect ? 1 : 0;

            //会员折扣
            $member_discount = Db::name('user_level l')
                ->join('user u', 'u.level = l.id')
                ->where(['u.id' => $user_id])
                ->value('discount');
            $price_array = [];
            //处理会员折扣价格
            if ($goods->is_member > 0 && $member_discount > 0) {
                //会员价格
                foreach ($goods->goods_item as $item => $value){
                    $goods->goods_item[$item]['member_price'] = 0;
                    if($member_discount){
                        $member_price =  round($value['price'] * $member_discount / 10,2);
                        $goods->goods_item[$item]['member_price'] = $member_price;
                        $price_array[] = $member_price;
                    }
                }
                $price_array && $goods->member_price = min($price_array);
            }
            //多规格，按最高的价格计算积分
            if($price_array && 2 === $goods->give_integral_type){
                $price = $price_array ? max($price_array) : $goods->max_price;
                $goods->order_give_integral = intval($price * $goods->give_integral / 100);
            }
        }
        //猜你喜欢
        $goods->Like();
        //商品规格
        $goods->GoodsSpec();
        $goods->visible(array_filter([
                'id','name','image','video','stock','remark','content','sales_sum','poster','integral',
                'min_price','max_price','market_price','is_collect','goods_spec','goods_image',
                'goods_item','activity','member_price','is_express','is_selffetch','market_price'
            ]));

        $market_price_array = array_column($goods->goods_item->toarray(),'market_price');
        $goods->market_price = max($market_price_array);
        $price_array = array_column($goods->goods_item->toarray(),'price');
        $goods->min_price = min($price_array);
        $goods->max_price = max($price_array);

        $goods->poster = !empty($goods->poster) ? UrlServer::getFileUrl($goods->poster) : '';
        // // 商品虚拟浏览量
        // $goods->click_count += $goods->virtual_click;
        // 预估佣金
        $goods = $goods->toArray();
        $goods['distribution'] = self::getDistribution($goods['max_price'], $user_id);
        return $goods;
    }


    /**
     * 计算最高可得预估佣金
     * @return array
     */
    public static function getDistribution($price, $userId)
    {
        $earnings = 0;
        //是否开启分销
        $isShow = ConfigServer::get('distribution', 'is_open', 0);
        $level = ConfigServer::get('distribution', 'level', 0);
        $first_ratio = ConfigServer::get('distribution', 'first_ratio', 0);//一级
        $second_ratio = ConfigServer::get('distribution', 'second_ratio', 0);//二级
        if($isShow==1){
            if($level==1){
                $earnings = max($earnings, round($price * $first_ratio / 100, 2));
            }
            if($level==2){
                $earnings = max($earnings, round($price * $first_ratio / 100, 2));
                $earnings = max($earnings, round($price * $second_ratio / 100, 2));
            }
        }
        return $earnings;
    }


    //平台推荐
    public static function getNewList($user_id,$page,$size){
        $goods = new Goods();
        $goods_count = $goods
                    ->where(['delete_time'=>0,'status'=>1,'is_new'=>1])
                    ->count();

        $goods_list = $goods
                    ->where(['delete_time'=>0,'status'=>1,'is_new'=>1])
                    ->field('id,name,image,min_price as price,integral,market_price,sales_sum+virtual_sales_sum as sales_sum')
                    ->order('sort desc,id desc')
                    ->page($page,$size)
                    ->select();

        $more = is_more($goods_count,$page,$size);  //是否有下一页

        $data = [
            'list'          => $goods_list,
            'page_no'       => $page,
            'page_size'     => $size,
            'count'         => $goods_count,
            'more'          => $more
        ];
        return $data;
    }

    //专区商品
    public static function activityGoodsList($id)
    {
        $where[] = ['AG.delete_time', '=', 0];
        $where[] = ['G.delete_time', '=', 0];
        $where[] = ['G.status', '=', 1];
        $where[] = ['activity_id', '=', $id];

        $goods = new Goods();
        $list = $goods->alias('G')
            ->join('activity_goods AG', 'G.id = AG.goods_id')
            ->where($where)
            ->field('G.id,G.name,G.image,G.min_price as price,sales_sum+virtual_sales_sum as sales_sum,G.market_price,AG.activity_id')
            ->select();
        return $list;
    }
}